package com.neihanduanzi.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.neihanduanzi.BaseActivity;
import com.neihanduanzi.R;
import com.neihanduanzi.model.Comments;
import com.neihanduanzi.model.RecommendBean;
import com.neihanduanzi.model.User;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * Created by 凸显 on 2016/10/30.
 */

public class RecommendListAdapter extends RecyclerView.Adapter<RecommendListAdapter.BaseViewHolder> {
    private Context mContext;
    private List<RecommendBean> mList;
    private final SharedPreferences sharedPreferences;

    public RecommendListAdapter(Context context, List<RecommendBean> list) {
        mContext = context;
        mList = list;
        sharedPreferences = mContext.getSharedPreferences("FontSetting", Context.MODE_PRIVATE);
    }

    @Override
    public int getItemViewType(int position) {
        int type = 0;
        if (mList != null) {
            type = mList.get(position).getType();
            if (type == 3) {
                if (mList.get(position).getImage() == null) {
                    type = 4;
                }
            }
        }
        return type;
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mContext);

        View view = inflater.inflate(R.layout.recommend_item_view, parent, false);
        FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.recommend_content_layout);
        BaseViewHolder baseViewHolder = null;
        switch (viewType) {
            case 2://视频
                View childView = inflater.inflate(R.layout.recommend_item_child_video_view, null);
                frameLayout.addView(childView);
                baseViewHolder = new VideoViewHolder(view);
                break;
            case 3://图片
                View childViewImg = inflater.inflate(R.layout.recommend_item_child_image_view, null);
                frameLayout.addView(childViewImg);
                baseViewHolder = new OtherViewHolder(view);
                break;
            case 4://段子
                baseViewHolder = new BaseViewHolder(view);
                break;
            default:
                baseViewHolder = new BaseViewHolder(view);
                break;
        }
        return baseViewHolder;
    }

    @Override
    public void onBindViewHolder(BaseViewHolder holder, int position) {

        holder.bindView(mList.get(position));
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public  class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private final RelativeLayout mRelativeLayoutComment;
        private ImageView mImageUser;
        private TextView mTextUserName;
        private TextView mTextContent;
        private TextView mTextCategory;
        private ImageView mImageComment;
        private TextView mTextCommentName;
        private CheckBox mCheckCommentDigg;
        private ImageView mImageCommentShare;
        private TextView mTextCommentContent;
        private CheckBox mCheckDigg;
        private CheckBox mCheckBury;
        private RadioButton mRadioHotComment;
        private RadioButton mRadioShare;
        private RecommendBean mRecommendBean;


        public BaseViewHolder(View itemView) {
            super(itemView);
            mImageUser = ((ImageView) itemView.findViewById(R.id.recommend_item_user_img));
            mTextUserName = ((TextView) itemView.findViewById(R.id.recommend_item_user_name));
            mTextContent = ((TextView) itemView.findViewById(R.id.recommend_item_text));
            mTextCategory = ((TextView) itemView.findViewById(R.id.recommend_item_category));
            mImageComment = ((ImageView) itemView.findViewById(R.id.recommend_item_comment_img));
            mTextCommentName = ((TextView) itemView.findViewById(R.id.recommend_item_comment_name));
            mCheckCommentDigg = ((CheckBox) itemView.findViewById(R.id.recommend_item_comment_digg));
            mImageCommentShare = ((ImageView) itemView.findViewById(R.id.recommend_item_comment_share));
            mTextCommentContent = ((TextView) itemView.findViewById(R.id.recommend_item_comment_content));
            mCheckDigg = ((CheckBox) itemView.findViewById(R.id.recommend_item_digg));
            mCheckBury = ((CheckBox) itemView.findViewById(R.id.recommend_item_bury));
            mRadioHotComment = ((RadioButton) itemView.findViewById(R.id.recommend_item_hot_comment));
            mRadioShare = ((RadioButton) itemView.findViewById(R.id.recommend_item_share));
            mRelativeLayoutComment = ((RelativeLayout) itemView.findViewById(R.id.recommend_item_comment_view));

            itemView.setOnClickListener(this);
            SharedPreferences sharedPreferences = mContext.getSharedPreferences("FontSetting", Context.MODE_PRIVATE);
            float font1 = sharedPreferences.getFloat("Font1", 18);
            float font2 = sharedPreferences.getFloat("Font2", 20);
            mTextContent.setTextSize(font1);
        }


        public void bindView(final RecommendBean recommendBean) {
            mRecommendBean=recommendBean;

            User user = recommendBean.getUser();
            if (user != null) {
                Picasso picasso = Picasso.with(mImageUser.getContext());
                picasso.load(user.getAvatarUrl())
                        .error(R.mipmap.index_top_left)
                        .placeholder(R.mipmap.index_top_left)
                        .into(mImageUser);
                mTextUserName.setText(user.getUserName());
            }
            mRadioShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(recommendBean);
                }
            });

            mTextCategory.setText(recommendBean.getCategory_Name());

            String title = recommendBean.getTitle();
            if (TextUtils.isEmpty(title)){
                mTextContent.setVisibility(View.GONE);
            }else {
                mTextContent.setText(title);
            }

            mCheckDigg.setText(recommendBean.getDiggCount() + "");
            mCheckBury.setText(recommendBean.getBuryCount() + "");
            mRadioShare.setText(recommendBean.getShareCount() + "");
            mRadioHotComment.setText(recommendBean.getCommentCount() + "");

            Comments comments = recommendBean.getComments();
            if (comments != null) {
                mRelativeLayoutComment.setVisibility(View.VISIBLE);
                Picasso.with(mImageComment.getContext()).load(comments.getImgUrl()).into(mImageComment);
                mCheckCommentDigg.setText(comments.getDiggCount() + "");
                mTextCommentContent.setText(comments.getContent());
                mTextCommentName.setText(comments.getUserName());

            } else {
                mRelativeLayoutComment.setVisibility(View.GONE);
            }

        }


        @Override
        public void onClick(View v) {
            if (mRecommendBean != null) {
                Gson gson = new Gson();
                String s = gson.toJson(mRecommendBean);
                Intent intent = new Intent(v.getContext(), BaseActivity.class);
                intent.putExtra("Data", s);
                intent.putExtra("type",getItemViewType());
                intent.putExtra("group_id",mRecommendBean.getGroupId());
                v.getContext().startActivity(intent);
            }
        }
    }

    public  class VideoViewHolder extends BaseViewHolder implements SurfaceHolder.Callback, View.OnClickListener {
        private final ProgressBar mProgressBar;
        private SurfaceView mSurfaceView;
        private ImageView mImageContent;
        private ImageView mImagePlay;
        private TextView mTextPlayCount;
        private TextView mTextTime;
        private MediaPlayer mPlayer;
        private int currentPosition; //当前视频播放的位置
        private String videoUrl;
        private RecommendBean mRecommendBean;

        public VideoViewHolder(View itemView) {
            super(itemView);
            mImageContent = (ImageView) itemView.findViewById(R.id.recommend_item_video_img);
            mImagePlay = (ImageView) itemView.findViewById(R.id.recommend_item_video_play);
            mSurfaceView = (SurfaceView) itemView.findViewById(R.id.recommend_item_video_surfaceview);
            mTextPlayCount = (TextView) itemView.findViewById(R.id.recommend_item_video_play_count);
            mTextTime = (TextView) itemView.findViewById(R.id.recommend_item_video_time);
            mProgressBar = ((ProgressBar) itemView.findViewById(R.id.recommend_item_video_progress));
            mPlayer = new MediaPlayer();
            mPlayer.start();

        }


        @Override
        public void bindView(RecommendBean recommendBean) {
            super.bindView(recommendBean);
            mRecommendBean=recommendBean;
            //视频网址
            videoUrl = recommendBean.getV360pVideo().getUrl_list().get(0).getUrl();
            Log.d(TAG, "VideoUrl : " + videoUrl);
            String ImgUrl = recommendBean.getCover().getUrl_list().get(0).getUrl();
//            String imageUrl = recommendBean.getImageUrl();
            if (ImgUrl != null) {
                Picasso.with(mImageContent.getContext())
                        .load(ImgUrl)
                        .into(mImageContent);
            }

            SurfaceHolder holder = mSurfaceView.getHolder();
            holder.addCallback(this);

            mImagePlay.setOnClickListener(this);
            int duration = mPlayer.getDuration();
            String s = millisToString(duration);
            mTextTime.setText(s);

            int playCount = recommendBean.getPlayCount();
            SpannableString string=new SpannableString(playCount+"次播放");

            string.setSpan(new ForegroundColorSpan(0xffff82A0),0,string.length()-3,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            mTextPlayCount.setText(string);
        }

        /**
         * @param millis   要转化的毫秒数。
         * @return 返回时间字符串：小时/分/秒/毫秒的格式（如：24903600 --> 06小时55分03秒600毫秒）。
         */

        private   String millisToString(long millis) {

            int h = 0;

            int  m = 0;

            int s = 0;

            long hper = 60 * 60 * 1000;
            long mper = 60 * 1000;
            long sper = 1000;

            h= (int) (millis/hper);
            if (h>0){
                m= (int) ((millis-(h*hper))/mper);

                if (m>0){
                    s= (int) ((millis-(h*hper)+(m*mper))/sper);
                }else {
                    s= (int) ((millis-(h*hper))/sper);
                }
            }else {
                m= (int) (millis/mper);

                if (m>0){
                    s= (int) ((millis-(m*mper))/sper);
                }else {
                    s= (int) (millis/sper);
                }
            }


            return h+":"+ m+":"+s;

        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {

        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (mPlayer != null && mPlayer.isPlaying()) {

                //获取当前视频播放的位置
                currentPosition = mPlayer.getCurrentPosition();
                mPlayer.stop();
                mImageContent.setVisibility(View.VISIBLE);
                mImagePlay.setVisibility(View.VISIBLE);

            }
        }


                @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.recommend_item_video_play:
                    btnPlayVideo();
                    break;
                default:
                    super.onClick(v);
                    break;
            }

        }

        private void btnPlayVideo() {
            // TODO: 点击播放视频
            if (mPlayer.isPlaying()) {
                mPlayer.stop();
            }
            mImagePlay.setVisibility(View.INVISIBLE);
            mProgressBar.setVisibility(View.VISIBLE);
            mPlayer.reset();

            // 1. 切换显示的SurfaceView
            mPlayer.setDisplay(mSurfaceView.getHolder());
            try {
                if (videoUrl != null) {
                    mPlayer.setDataSource(videoUrl);
//                    int duration = mPlayer.getDuration();
//                    String s = millisToString(duration, false, false);
//                    mTextTime.setText(s);

                    // 2. 设置视频地址，开始加载
                    mPlayer.prepareAsync();
//                            sPlayingPosition = itemPosition;

                    mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mProgressBar.setVisibility(View.INVISIBLE);
                            mImageContent.setVisibility(View.INVISIBLE);
                            //[4]开始播放
                            mPlayer.start();
                            //[5]继续上次的位置继续播放
//                            mPlayer.seekTo(currentPosition);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public  class OtherViewHolder extends BaseViewHolder {
        private ProgressBar mProgressBar;
        private ImageView mImageContent;
        private ImageView mImageGif;
        private RecommendBean mRecommendBean;


        public OtherViewHolder(View itemView) {
            super(itemView);
            mProgressBar = (ProgressBar) itemView.findViewById(R.id.recommend_item_image_bar);
            mImageGif = (ImageView) itemView.findViewById(R.id.recommend_item_image_gif);
            mImageContent = (ImageView) itemView.findViewById(R.id.recommend_item_image_content);
        }

        

        @Override
        public void bindView(RecommendBean recommendBean) {
            super.bindView(recommendBean);
            mRecommendBean=recommendBean;
            int isGif = recommendBean.getIsGif();
            RecommendBean.Image image = recommendBean.getImage();
            String url = image.getUrl_list().get(0).getUrl();
//            String url = recommendBean.getImageUrl();
            if (url != null) {
                Picasso.with(mImageContent.getContext())
                        .load(url)
                        .into(mImageContent);
            }
            if (isGif == 1) {
                RecommendBean.Image imageGif = recommendBean.getImageGif();
                String urlGif = imageGif.getUrl_list().get(0).getUrl();
                mImageGif.setVisibility(View.VISIBLE);
                Log.d(TAG, "url: " + urlGif);
                Glide.with(mImageContent.getContext())
                        .load(urlGif)
                        .asGif()
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .into(mImageContent);
            }
        }
    }


}
